const Vue = require('vue')
const VueServerRenderer = require('vue-server-renderer')
const Koa = require('koa')
const fs = require('fs')
const path = require('path')
const Router = require('@koa/router')
const KoaStatic = require('koa-static')
let app = new Koa() // 创建一个服务实例
let router = new Router()

const serverBundle = require('./dist/vue-ssr-server-bundle.json')
//client-entry的打包信息
const clientManifest = require('./dist/vue-ssr-client-manifest.json')
const template = fs.readFileSync('./dist/index.ssr.html', 'utf8')
let render = VueServerRenderer.createBundleRenderer(serverBundle, {
  template,
  clientManifest
})
router.get('/', async ctx => {
  // 里面包含浏览器和服务端的 req/res的一些信
  ctx.body = await new Promise((resolve, reject) => {
    render.renderToString((err, html) => {
      resolve(html)
    })
  })
})
router.get('*', async ctx => {
  // 里面包含浏览器和服务端的 req/res的一些信
  ctx.body = await new Promise((resolve, reject) => {
    render.renderToString((err, html) => {
      resolve(html)
    })
  })
})

app.use(router.routes()) // 将路由注册上
app.use(KoaStatic(path.resolve(__dirname, 'dist')))

//

app.listen(3000)
